package com.ruoyi.common.flowable;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.Map;

@Component
public class FlowableServiceUrl {

    private static final Logger log = LoggerFactory.getLogger(FlowableServiceUrl.class);

    @Autowired
    private RestTemplate restTemplate;

    @Value("${flowable.url}")
    private String url;//"http://localhost:9080/flowable/"
    private String prefix = "workflow/";

    private String createNewUser;
    private String addGroupMember;
    private String deleteGroupMember;

    private String deleteUser;
    private String createNewGroup;
    private String deleteGroup;
    private String startProcessInstanceByKey;

    private String models = "";
    private String queryUnDoTaskList = "";
    private String queryDoneTaskList = "";
    private String completeTask = "";
    private String queryHistoryTask = "";
    private String queryProcessDefinitionList = "";
    private String deployProcessByModel = "";
    private String deleteProcessDeploy = "";
    private String suspendOrActive = "";
    private String deployProcessByFile = "";
    private String deleteModel = "";
    private String delegateTask = "";
    private String terminateProcess = "";
    private String backToStep = "";


    @PostConstruct
    public void init() {
        //对应ModelsResource
        //查看单个模型信息：http://localhost:9080/flowable/app/rest/models/4b6e4813-360f-11eb-998c-9453305755e8
        //查看单个模型图片：http://localhost:9080/flowable/app/rest/models/4b6e4813-360f-11eb-998c-9453305755e8/thumbnail
        //删除模型 RequestMethod.DELETE http://localhost:9080/flowable/app/rest/models/{modelId}
        createNewUser = url + prefix + "createNewUser";//
        addGroupMember = url + prefix + "addGroupMember";//
        deleteGroupMember = url + prefix + "deleteGroupMember";//
        deleteUser = url + prefix + "deleteUser";//
        createNewGroup = url + prefix + "createNewGroup";//
        deleteGroup = url + prefix + "deleteGroup";//
        startProcessInstanceByKey = url + prefix + "startProcessInstanceByKey";//
        models = url + "app/rest/models?filter=processes&modelType=0&sort=modifiedDesc";
        startProcessInstanceByKey = url + prefix + "startProcessInstanceByKey";
        queryUnDoTaskList = url + prefix + "queryUnDoTaskList";
        queryDoneTaskList = url + prefix + "queryDoneTaskList";
        completeTask = url + prefix + "completeTask";
        queryHistoryTask = url + prefix + "queryHistoryTask";
        queryProcessDefinitionList = url + prefix + "queryProcessDefinitionList";
        deployProcessByModel = url + prefix + "deployProcessByModel";
        deleteProcessDeploy = url + prefix + "deleteProcessDeploy";
        suspendOrActive = url + prefix + "suspendOrActive";
        deployProcessByFile = url + prefix + "deployProcessByFile";
        deleteModel = url + prefix + "deleteModel";
        delegateTask = url + prefix + "delegateTask";
        terminateProcess = url + prefix + "terminateProcess";
        backToStep = url + prefix + "backToStep";
        

    }

    public String getCreateNewUser() {
        return createNewUser;
    }

    public String getAddGroupMember() {
        return addGroupMember;
    }

    public String getDeleteGroupMember() {
        return deleteGroupMember;
    }

    public String getDeleteUser() {
        return deleteUser;
    }

    public String getCreateNewGroup() {
        return createNewGroup;
    }

    public String getDeleteGroup() {
        return deleteGroup;
    }

    public String getStartProcessInstanceByKey() {
        return startProcessInstanceByKey;
    }
    public String getModels() {
        return models;
    }

    public String getQueryUnDoTaskList() {
        return queryUnDoTaskList;
    }

    public String getQueryDoneTaskList() {
        return queryDoneTaskList;
    }

    public String getCompleteTask() {
        return completeTask;
    }

    public String getQueryHistoryTask() {
        return queryHistoryTask;
    }

    public String getQueryProcessDefinitionList() {
        return queryProcessDefinitionList;
    }

    public String getDeployProcessByModel() {
        return deployProcessByModel;
    }

    public String getDeleteProcessDeploy() {
        return deleteProcessDeploy;
    }

    public String getSuspendOrActive() {
        return suspendOrActive;
    }

    public String getDeployProcessByFile() {
        return deployProcessByFile;
    }

    public String getDeleteModel() {
        return deleteModel;
    }

    public String getDelegateTask() {
        return delegateTask;
    }

    public String getTerminateProcess() {
        return terminateProcess;
    }

    public String getBackToStep() {
        return backToStep;
    }


    public JSONObject get(String url) {
        //get请求2  动态匹配值
//		String url = "http://localhost:9080/flowable/app/rest/models?filter={filter}&modelType={modelType}&sort={sort}";
//		Map<String, Object> varMap = new HashMap<String, Object>();
//		varMap.put("filter", "processes");
//		varMap.put("modelType", 0);
//		varMap.put("sort", "modifiedDesc");
//		ResponseEntity<String> res =  restTemplate.getForEntity(queryModelList_url, String.class, varMap);
//		String jsonStr = res.getBody();
        //get请求
        ResponseEntity<String> res = restTemplate.getForEntity(url, String.class);
        JSONObject json = JSON.parseObject(res.getBody());
        return json;
    }

    public JSONObject post(String url, Map<String,Object> params){
        String paramsJson = JSON.toJSONString(params);
        //post请求
        String result = restTemplate.postForObject(url, paramsJson, String.class);
        JSONObject json = JSON.parseObject(result);
        return json;
    }

    /**
     * 一般用作修改
     * 如 String uri = "http://localhost:8080/springrestexample/employees/{id}";
     *     Map<String, String> params = new HashMap<String, String>();
     *     params.put("id", "2");
     *     EmployeeVO updateParams = new EmployeeVO(2, "New Name", "Gilly", "test@email.com");
     * @param url
     * @param params
     */
    public void put(String url, Map<String,Object> updateParams, Map<String,Object> params){
        RestTemplate restTemplate = new RestTemplate();
        restTemplate.put(url, updateParams, params);
    }

    /**
     * 用作删除
     * 如:url = "http://localhost:8080/springrestexample/employees/{id}";
     * Map<String, String> params = new HashMap<String, String>();
     * params.put("id", "2");
     * @param url
     * @param params
     */
    public void delete(String url, Map<String, String> params){
        RestTemplate restTemplate = new RestTemplate();
        restTemplate.delete(url,  params );
    }

    public AjaxResult doPost(String url, Object object){
        String paramsJson = JSONUtil.toJsonStr(object);
        log.info(">>>>请求第三方服务[" + url + "]请求报文:" + paramsJson);
        String jsonStr = HttpUtil.post(url, paramsJson);
        log.info("<<<<请求第三方服务[" + url + "]响应报文:" + jsonStr);
        return JSONUtil.toBean(jsonStr, AjaxResult.class);
    }

    public Map<String,Object> doPostOfbizQuery(String url, Object object){
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser user = loginUser.getUser();
        Map<String,Object> context = new HashMap<>();
        context.put("header",user);
        context.put("body",object);
        String paramsJson = JSONUtil.toJsonStr(context);
        log.info(">>>>请求ofbiz服务[" + url + "]请求报文:" + paramsJson);
        String jsonStr = HttpUtil.post(url, paramsJson);
        log.info("<<<<请求ofbiz服务[" + url + "]响应报文:" + jsonStr);
        return JSONUtil.toBean(jsonStr, Map.class);
    }

    public int doPostOfbizUpdate(String url, Object object){
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser user = loginUser.getUser();
        //content.setCreatedByUserLogin(String.valueOf(user.getUserId()));
        Map<String,Object> context = new HashMap<>();
        context.put("header",user);
        context.put("body",object);
        String paramsJson = JSONUtil.toJsonStr(context);
        log.info(">>>>请求ofbiz服务[" + url + "]请求报文:" + paramsJson);
        String jsonStr = HttpUtil.post(url, paramsJson);
        log.info("<<<<请求ofbiz服务[" + url + "]响应报文:" + jsonStr);
        cn.hutool.json.JSONObject jsonObject = JSONUtil.parseObj(jsonStr);
        if (jsonObject != null && "success".equals(jsonObject.get("responseMessage"))) {
            return 1;
        }
        return 0;
    }
}
